#include "TcpServer.h"

TcpServer::TcpServer(std::string &ip, uint16_t &port)
{
    acceptor_ = new Acceptor(&loop_, ip, port);
    acceptor_->setnewConnectioncb(std::bind(&TcpServer::newConnection, this, std::placeholders::_1));
}

void TcpServer::start()
{
    loop_.run();
}
TcpServer::~TcpServer()
{
    delete acceptor_;
    for (auto &aa : conns_)
    {
        delete aa.second;
    }
}

void TcpServer::newConnection(Socket *clientsock)
{
    Connection *conn = new Connection(&loop_, clientsock);

    conn->setCloseCallBack(std::bind(&TcpServer::closeconnection, this, std::placeholders::_1));
    conn->setErrorCallBack(std::bind(&TcpServer::errorconnection, this, std::placeholders::_1));
    conn->setonmessagecb(std::bind(&TcpServer::onmessage, this, std::placeholders::_1, std::placeholders::_2));
    printf("accept client(fd=%d,ip=%s,port=%d) ok.\n", conn->fd(), conn->getiP().c_str(), conn->getport());
    conns_[conn->fd()] = conn;
}

void TcpServer::closeconnection(Connection *conn) // TCP断开连接的回调函数 ，提供channel 回调
{
    printf("client(eventfd=%d) disconnected.\n", conn->fd());
    // close(conn->fd()); // 关闭客户端的fd。
    conns_.erase(conn->fd());
    delete conn;
}
void TcpServer::errorconnection(Connection *conn) // TcP连接错误的回调函数，提供Channel 回调
{
    printf("client(eventfd=%d) error.\n", conn->fd());
    // close(conn->fd()); // 关闭客户端的fd。
    conns_.erase(conn->fd());
    delete conn;
}

void TcpServer::onmessage(Connection *conn, std::string message)
{
    message = "reply" + message; // 得到处理后的结果

    int len = message.size();
    std::string tempbuf((char *)&len, 4);
    tempbuf.append(message);
    // conn->outputbuffer_ = conn->inputbuffer_;
    // inputbuffer_.clear();
    // send(conn->fd(), tempbuf.data(), tempbuf.size(), 0);
    conn->send(tempbuf.data(), tempbuf.size());
}